const db = require('../config/db');

const checkEventConflict = async (userId, startTime, endTime, excludeEventId = null) => {
  try {
    // 检查个人日程冲突
    const [personalEvents] = await db.execute(
      `SELECT * FROM events 
       WHERE user_id = ? 
       AND event_type = 'personal'
       AND id != ?
       AND (
         (start_time <= ? AND end_time > ?) OR
         (start_time < ? AND end_time >= ?) OR
         (start_time >= ? AND end_time <= ?)
       )`,
      [userId, excludeEventId || '', startTime, startTime, endTime, endTime, startTime, endTime]
    );

    // 检查公共日程冲突
    const [publicEvents] = await db.execute(
      `SELECT * FROM events 
       WHERE event_type = 'public'
       AND id != ?
       AND (
         (start_time <= ? AND end_time > ?) OR
         (start_time < ? AND end_time >= ?) OR
         (start_time >= ? AND end_time <= ?)
       )`,
      [excludeEventId || '', startTime, startTime, endTime, endTime, startTime, endTime]
    );

    const conflicts = [...personalEvents, ...publicEvents];
    
    return {
      hasConflict: conflicts.length > 0,
      conflicts
    };
  } catch (error) {
    throw new Error('检查日程冲突失败');
  }
};

module.exports = { checkEventConflict };